package com.qingxin.ui.bean;

import java.io.File;
import java.io.FilenameFilter;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.qingxin.ui.service.UIDynamicReplacerImpl;

/**
 * 加载UI配置的监听器，用于初始化
 */
public class UIInitListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		UILoader.clear();
	}
	
	@Override
	public void contextInitialized(ServletContextEvent event) {
		if(!UIParam.DEBUG){//非调试模式
			InitThread thread = new InitThread();
			thread.start();
		}
	}

	//配置文件加载线程
	//该类作用在于加载配置文件时不影响服务器主线程的启动
	static class InitThread extends Thread {
		@Override
		public void run() {
			UIDynamicReplacerImpl dynamicReplacer = new UIDynamicReplacerImpl();
			try {
				File directory = new File(this.getClass().getResource(UIParam.CONFIG_PATH).toURI());
				File[] configs = directory.listFiles(new LayoutConfigFilter(UIParam.CONFIG_SUFFIX));
				for(File config : configs){
					String code = config.getName();
					code = code.substring(0, code.length() - UIParam.CONFIG_SUFFIX.length());
					UILoader.getUILayout(code, dynamicReplacer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	//配置文件过滤器
	static class LayoutConfigFilter implements FilenameFilter{
		private String suffix;
		public LayoutConfigFilter(String suffix) {
			this.suffix = suffix;
		}
		@Override
		public boolean accept(File dir, String name) {
			return name.endsWith(suffix);
		}
	}
	
}
